package cn.tedu.truetaste.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.tedu.truetaste.service.IMemberLoginService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class MemberLoginServiceImpl implements IMemberLoginService {

    @Value("${wx.appId}")
    private String appId;

    @Value("${wx.secret}")
    private String secret;

    @Value("${wx.templateId}")
    private String templateId;

    private String openIdData;

    @Override
    public String getUserOpenId(String code) {
        String authUrl="https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
        authUrl = authUrl + "&appid=" + appId + "&secret=" + secret + "&js_code=" + code;
        System.out.println("30000,"+authUrl);
        String result = HttpUtil.get(authUrl);

        JSONObject jsonObject = JSONUtil.parseObj(result);
        System.out.println(jsonObject);
        String openId = jsonObject.getStr("openid");
        openIdData = openId;
        return openId;
    }

    @Override
    public String getTokenId() {
            String tokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
            tokenUrl = tokenUrl + "&appid=" + appId + "&secret=" + secret;
            String result = HttpUtil.get(tokenUrl);
            JSONObject jsonObject = JSONUtil.parseObj(result);
            String tokenData = jsonObject.get("access_token").toString();
            return tokenData;
    }

    @Override
    public void send(String token) {
        String msgUrl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send";
        msgUrl = msgUrl + "?access_token=" + token;
        // 设置模板参数
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("touser", openIdData);                 // 接收方
        paramMap.put("template_id", templateId);        // 模板id
        paramMap.put("page","pages/self/self");         // 消息中要跳转的页面
        // 设置data 模板内容
        HashMap<String, Object> data = new HashMap<>();
        data.put("amount27", formatParam("100"));
        data.put("character_string29", formatParam("001"));
        data.put("time31", formatParam("2023-12-14"));
        paramMap.put("data", data);
        // 转json字符串
        String jsonObject = JSONUtil.toJsonStr(paramMap);
        String result= HttpUtil.post(msgUrl, jsonObject);
        System.out.println("3008,"+result);
    }

    public HashMap<String, Object> formatParam(String value){
        HashMap<String, Object> data = new HashMap<>();
        data.put("value", value);
        return data;
    }

}
